import { Grid, Input, InputNumber, Message, Radio, Select, Tag } from '@arco-design/web-react';
import DetailItem from '@src/components/detailItem';
import DetailModal from '@src/components/detailModal';
import LoadingMask from '@src/components/loadingMask';
import { useEffect, useState } from 'react';
import { shallowEqual, useDispatch, useSelector } from 'react-redux';
import { createStoreDetailKey, detailRequest, detailUpdate } from '../../../redux/detailReducer';
import { AppStore, ValidateRule } from '../../../types';
import { tagStyleOptions } from '../../../utils/defaultData';
import useDict, { dictDataOptions } from '../../../utils/dict';
import { cloneDeep, findTagColor, validateField } from '../../../utils/utils';
import { DictData } from './types';

const { Col, Row } = Grid;
interface Props {
  id: string | number;
  dictType: string;
  onCancel: (update?: boolean) => void;
}

const model = 'system';
const table = 'dict/data';

// 字段验证规则
const rule: ValidateRule = {};
// 系统开关 状态
const SYS_NORMAL_DISABLED = 'sys_normal_disable';

export default function DictDataDetailPage({ id, dictType, onCancel }: Props) {
  // 页面标题 显示在二级菜单下面
  const pageTitle = (id === 'create' ? '新增' : '修改') + '字典数据';
  const dispatch = useDispatch();
  const dictDatas = useDict(SYS_NORMAL_DISABLED);
  // 每次编辑时修改的数据 可加默认值
  const [detailData, setDetailData] = useState<DictData | null | undefined>(
    Object.assign({ default: true, status: '0' }, { dictType })
  );
  const [errorData, setErrorData] = useState<{ [x: string]: string }>({});
  // --------------额外数据--------------------------------------
  // -----------------------------------------------------------
  // 当前详情
  const detail = useSelector(
    (state: AppStore) => state.detail?.[createStoreDetailKey({ model, table, id: id.toString() })],
    shallowEqual
  );

  // 页面初次渲染时获取数据
  useEffect(() => {
    if (id && id !== 'create') {
      handleRefreshData();
    }
  }, []); //eslint-disable-line

  // 页面详情数据获取到后存入编辑数据
  useEffect(() => {
    if (id !== 'create' && detail?.loaded && detail?.result && detail?.result?.dictCode) {
      let result = detail?.result;
      setDetailData(result);
      // 需要依赖详情数据加载别的数据的 在这里写
    }
  }, [detail]); //eslint-disable-line

  // 当前详情数据请求
  function handleRefreshData(forceRefresh?: boolean, callback?: (code?: number, msg?: string) => void) {
    if (id && id !== 'create') {
      dispatch(detailRequest({ model, table, id: id.toString(), forceRefresh, callback }));
    }
  }
  // 任意字段修改时存入编辑数据
  function handleChange(key: string, value: any) {
    setErrorData({});

    let data: any = cloneDeep(detailData);
    data[key] = value;
    setDetailData(data);
  }

  // 保存
  async function handleSave() {
    let validateRes = validateField(detailData, rule);
    setErrorData(validateRes);
    if (Object.keys(validateRes).length) return;

    LoadingMask.show('正在保存...');
    dispatch(
      detailUpdate({
        model,
        table,
        id: id.toString(),
        detail: detailData,
        callback(code, msg) {
          let _msg = code === 200 ? Message.success : Message.warning;
          LoadingMask.hide();
          onCancel(true);
          _msg(msg ?? '');
        },
      })
    );
  }
  //----------------额外操作 / 数据-------------------

  //-------------------------------------------------

  return (
    <DetailModal title={pageTitle} show onConfirm={handleSave} onCancel={() => onCancel()}>
      <DetailItem label="数据标签" labelSpan={4} outlet={4} error={errorData.dictLabel}>
        <Input value={detailData?.dictLabel} onChange={(v) => handleChange('dictLabel', v)} />
      </DetailItem>
      <DetailItem label="数据键值" labelSpan={4} outlet={4} error={errorData.dictValue}>
        <Input value={detailData?.dictValue} onChange={(v) => handleChange('dictValue', v)} />
      </DetailItem>
      <DetailItem label="显示排序" labelSpan={8} outlet={2} error={errorData.dictSort}>
        <InputNumber value={detailData?.dictSort} onChange={(v) => handleChange('dictSort', v)} />
      </DetailItem>
      <DetailItem label="样式属性" labelSpan={8} outlet={2} error={errorData.cssClass}>
        <Input value={detailData?.cssClass} onChange={(v) => handleChange('cssClass', v)} />
      </DetailItem>
      <DetailItem label="回显样式" labelSpan={4} outlet={4} error={errorData.listClass}>
        <Row>
          <Col span={20}>
            <Select
              value={detailData?.listClass}
              options={tagStyleOptions}
              onChange={(v) => handleChange('listClass', v)}
            />
          </Col>
          <Col span={4} className="pl-4 pt-4">
            <Tag bordered color={findTagColor(detailData?.listClass)}>
              示例
            </Tag>
          </Col>
        </Row>
      </DetailItem>
      <DetailItem label="状态" labelSpan={8} outlet={2} error={errorData.status}>
        <Select
          value={detailData?.status}
          options={dictDataOptions(dictDatas[SYS_NORMAL_DISABLED])}
          onChange={(v) => handleChange('status', v)}
        />
      </DetailItem>
      <DetailItem label="是否默认" labelSpan={8} outlet={2} error={errorData.default}>
        <Radio.Group value={detailData?.default} onChange={(v) => handleChange('default', v)}>
          <Radio value={true}>是</Radio>
          <Radio value={false}>否</Radio>
        </Radio.Group>
      </DetailItem>
      <DetailItem label="备注" labelSpan={4} outlet={4} error={errorData.remark}>
        <Input.TextArea
          className="m-input-area"
          value={detailData?.remark}
          onChange={(v) => handleChange('remark', v)}
        />
      </DetailItem>
    </DetailModal>
  );
}
